package com.yifeng.repo.controller.excel.web;

import com.gomcarter.frameworks.base.json.ErrorCode;
import com.yifeng.repo.base.utils.servlet.RequestHelper;
import com.yifeng.repo.base.utils.servlet.ResponseHelper;
import com.yifeng.repo.controller.excel.loader.ExcelLoaderManager;
import com.yifeng.repo.controller.excel.loader.dto.DataTaskDto;
import com.yifeng.repo.controller.excel.loader.dto.DataTaskTypeEnum;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by daibing on 2022/12/29.
 */
public class ExcelLoaderServlet extends HttpServlet {
    public static final String LIST_DATA_TASK = "/listDataTask";
    public static final String GET_DATA_TASK = "/getDataTask";
    public static final String CLEAR_RUNNING_NUMBER = "/clearRunningNumber";
    private final ExcelLoaderManager excelLoaderManager;

    public ExcelLoaderServlet(ExcelLoaderManager excelLoaderManager) {
        this.excelLoaderManager = excelLoaderManager;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getRequestURI().endsWith(LIST_DATA_TASK)) {
            String type = req.getParameter("type");
            List<String> keys = excelLoaderManager.listDataTaskRequestKey(DataTaskTypeEnum.get(type));
            ResponseHelper.doWrite(resp, keys);
        } else if (req.getRequestURI().endsWith(GET_DATA_TASK)) {
            String requestKey = req.getParameter("requestKey");
            String type = req.getParameter("type");
            DataTaskDto dataTask = excelLoaderManager.getDataTask(requestKey, DataTaskTypeEnum.get(type));
            ResponseHelper.doWrite(resp, dataTask);
        } else if (req.getRequestURI().endsWith(CLEAR_RUNNING_NUMBER)) {
            Long runningNumber = excelLoaderManager.clearRunningNumber();
            ResponseHelper.doWrite(resp, runningNumber);
        } else {
            ResponseHelper.doError(resp, ErrorCode.noPermission.getCode(),
                    "http.method_post_not_supported from " + RequestHelper.getRemoteAddress(req));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

}
